<template>
  <div class="page-container">
    <BridgeVerticalTabNav />
    
    <div class="list-page">
      <!-- 搜索和操作区域 -->
      <div class="filter-area">
        <div class="search-area">
          <el-input
            v-model="searchValue"
            placeholder="请输入桥梁名称搜索"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="operation-area">
          <el-button 
            class="custom-button primary-button"
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>新增桥梁
          </el-button>
          <!-- <el-button 
            class="custom-button success-button"
            @click="router.push('/basic-data/two-pages/bridge')"
          >
            <el-icon><DataLine /></el-icon>健康数据
          </el-button> -->
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        height="calc(100vh - 250px)" 
        :header-cell-style="{ background: 'var(--el-bg-color-page)' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="桥梁名称" prop="bridgeName" min-width="150" />
        <el-table-column label="桥梁类型" prop="bridgeType" width="150" align="center" />
        <el-table-column label="所属区域" prop="region" min-width="170" align="center" />
        <el-table-column label="桥梁长度(米)" prop="bridgeLength" width="150" align="center" />
        <el-table-column label="桥梁宽度(米)" prop="bridgeWidth" width="150" align="center" />
        <el-table-column label="桥梁高度(米)" prop="bridgeHeight" width="150" align="center" />
        <el-table-column label="设计荷载(吨)" prop="designLoad" width="150" align="center" />
        <el-table-column label="建成日期" prop="buildDate" width="150" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.buildDate) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks" min-width="120" align="center">
          <template #default="scope">
              <span
               v-if="scope.row.remarks"
                class="remarks-text"
                @click="showRemarks(scope.row)"
              >{{ scope.row.remarks }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" link @click="handleAnalysis(scope.row)">分析</el-button>
            <el-button type="warning" link @click="handleMaintenance(scope.row)">保养</el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(scope.row)"
              v-perms="['bridge:basic:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑/新增弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        width="60%"
        top="5vh"
        destroy-on-close
        :show-header="false"
      >
      <div style="height: 500px;display: flex;justify-content: center;align-items: center;">
          <BridgeForm
          :id="String(currentRow.id)"
          :is-edit="dialogType === 'edit'"
          :edit-data="currentRow"
          @success="handleSuccess"
          @close="dialogVisible = false"
        />
      </div>
      </el-dialog>

      <!-- 添加备注信息弹窗 -->
      <el-dialog
        v-model="remarksDialogVisible"
        title="备注信息"
        width="40%"
      >
        <div style="white-space: pre-wrap;">{{ currentRemarks }}</div>
        <template #footer>
          <span >
            <el-button @click="remarksDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, DataLine } from '@element-plus/icons-vue'
import { getBridgeList, addBridge, updateBridge, deleteBridge, getBridgeById } from '@/api/bridge/bisc/bridge'
import type { DictDataQuery } from '@/api/system/dict/data/types'
import BridgeForm from './components/bridge-form.vue'
import BridgeVerticalTabNav from './components/BridgeVerticalTabNav.vue'
import dayjs from 'dayjs'

const router = useRouter()

// 查询参数
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  dictType: '',
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchValue = ref('')

// 弹窗控制
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')

// 表单数据
const formRef = ref()
const form = ref({
  id: '',
  bridgeName: '',
  bridgeType: '',
  buildTime: '',
  length: 0,
  navigationLevel: '',
  status: 1
})

// 表单校验规则
const rules = {
  bridgeName: [{ required: true, message: '请输入桥梁名称', trigger: 'blur' }],
  bridgeType: [{ required: true, message: '请选择桥梁类型', trigger: 'change' }],
  buildTime: [{ required: true, message: '请选择建成时间', trigger: 'change' }],
  length: [{ required: true, message: '请输入桥梁长度', trigger: 'blur' }],
  navigationLevel: [{ required: true, message: '请选择通航等级', trigger: 'change' }]
}

// 添加备注弹窗相关的响应式变量
const remarksDialogVisible = ref(false)
const currentRemarks = ref('')

// 获取列表数据
const getList = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchValue.value
    }
    const res = await getBridgeList(params)
    tableData.value = res.rows
    total.value = res.total
    console.log(tableData.value)
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getList()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    id: '',
    bridgeName: '',
    bridgeType: '',
    buildTime: '',
    length: 0,
    navigationLevel: '',
    status: 1
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row: any) => {
  try {
    console.log(row)
    const res = await getBridgeById(row.id)
    currentRow.value = res.data
    dialogType.value = 'edit'
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
  }
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该桥梁信息吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteBridge(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

// 新增的分析和保养按钮处理函数
const handleAnalysis = (row: any) => {
  router.push(`/basic-data/two-pages/bridge?bridgeId=${row.id}`)
}

const handleMaintenance = (row: any) => {
  router.push(`/basic-data/four-pages/bridge?bridgeId=${row.id}`)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // TODO: 调用保存API
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
      dialogVisible.value = false
      getList()
    }
  })
}

const currentRow = ref<{
  id?: string | number
  [key: string]: any
}>({})

const handleSuccess = () => {
  dialogVisible.value = false
  getList()
}

// 添加显示备注的方法
const showRemarks = (row: any) => {
  currentRemarks.value = row.remarks || '暂无备注'
  remarksDialogVisible.value = true
}

// 添加日期格式化函数
const formatDate = (date: string | number | Date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD')
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.list-page {
  flex: 1;
  padding: 20px;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: auto;
}

.filter-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: var(--el-bg-color-overlay);
  padding: 16px;
  border-radius: 4px;

  .search-input {
    width: 300px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
  background: var(--el-bg-color-overlay);
}

.el-dialog {
  border-radius: 12px;
  
  :deep(.el-dialog__body) {
    padding: 24px;
  }
}

.el-form-item {
  margin-bottom: 24px;
  margin-left: -20px;
  :deep(.el-form-item__label) {
    color: #606266;
    font-weight: 500;
  }
}

.operation-area {
  display: flex;
  gap: 12px;
  
  .custom-button {
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      width: 0;
      height: 0;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      transform: translate(-50%, -50%);
      transition: width 0.6s ease, height 0.6s ease;
    }
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      
      &::before {
        width: 300px;
        height: 300px;
      }
    }
    
    &:active {
      transform: translateY(1px);
    }
  }

  .primary-button {
    background: var(--el-color-primary);
    border-color: var(--el-color-primary);
    color: white;
    
    &:hover {
      background: var(--el-color-primary-light-3);
      border-color: var(--el-color-primary-light-3);
    }
  }

  .success-button {
    background: #42b983;
    border-color: #42b983;
    color: white;
    
    &:hover {
      background: #4cd69b;
      border-color: #4cd69b;
    }
  }
}

.remarks-text {
  display: inline-block;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--el-color-primary);
  cursor: pointer;
  
  &:hover {
    text-decoration: underline;
  }
}
</style>
